package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.INlifeCoreProdService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
/**
 *  新意健险核心产品
 */
@Controller
@RequestMapping("/nlifeCoreProduct")
public class NlifeCoreProductController {
	private static Logger logger = LogUtil.getLog(NlifeCoreProductController.class);
	@Resource
	private INlifeCoreProdService nlifeCoreProdService;
	
	@RequestMapping(value = "/list")
	public String list() throws Exception {
		logger.debug("forward newLifeCoreProduct successful....");
			return "nlifeProduct/nlifeCore/list";
	}
	
	/**
	 * 核心产品模板下载
	 */
	@RequestMapping(value = "/downloadCoreProd", method = RequestMethod.GET)
	public void downloadCoreProd(HttpServletResponse response,HttpServletRequest request ) throws IOException{
		String classPath=this.getClass().getResource("").getPath();
		String path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/coreProd_template.xls").replace("/WEB-INF", "");
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			//清空response
			response.reset();
			//设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		}catch (Exception e) {
			logger.info(e);
		}finally{
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}
	
	/**
	 * excel上传
	 */
	@RequestMapping(value = "/xlsImportNlifeCoreProdFileUpload")
	public void addNlifeCoreProdFile(@RequestParam MultipartFile[] myfiles,HttpServletResponse response, HttpSession session) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			if (myfiles.length < 1) {
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else{
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				inputStreams=nlifeCoreProdService.getFileInputStream(myfiles);
				nlifeCoreProdService.insertDataToDB(inputStreams.get(0),user,session);
				logger.info("读写成功");
				page.setResult("success");
				page.setMessage((String)session.getAttribute("result"));
			}
		} catch (Exception e) {
			logger.info("---------核心产品Excel导入失败",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	
}
